package com.ifengchao.service.impl;

import com.ifengchao.commonUtil.ServiceException;
import com.ifengchao.dao.iface.DealCreativesDao;
import com.ifengchao.dao.iface.DealOrderDao;
import com.ifengchao.pojo.PlanBean;
import com.ifengchao.service.DealCreativesService;
import com.ifengchao.util.MathUtil;
import com.ifengchao.util.zzy.ZhiZiYunUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by CSJ11 on 2017/8/29.
 * 创意更新数据
 */
@Service
public class DealCreativesServiceImpl implements DealCreativesService {

    private static final Logger logger = Logger.getLogger(DealCreativesServiceImpl.class);

    @Autowired(required = true)
    private DealCreativesDao dealCreativesDao;


    @Override
    @Transactional
    public void getCreativesByPlan() throws Exception {
        List<String> planIdList = dealCreativesDao.queryAllPlanId();
        if (null != planIdList && planIdList.size() > 0) {
            String[] planArr = planIdList.toArray(new String[planIdList.size()]);
            Calendar now = Calendar.getInstance();
            now.add(Calendar.DAY_OF_MONTH, -1);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String Datetime = sdf.format(now.getTime());

            Map<String, Object> parm = new HashMap<>();
            parm.put("starttime", Datetime);
            parm.put("endtime", Datetime);
            parm.put("planids", planArr);
            JSONObject planResult = new JSONObject();
            try {
                planResult = ZhiZiYunUtil.getZhiZiYunData("rtbreport/getCreativesByPlan", parm);

                if (null != planResult && (Boolean) planResult.get("status")) {
                    List<String> plList = new ArrayList<>();
                    JSONObject planObj = planResult.getJSONObject("response");
                    Iterator it = planObj.keySet().iterator();
                    while (it.hasNext()) {
                        String key = (String) it.next();
                        plList.add(key);
                    }
                    List<Map<String, Object>> propMaps = new ArrayList<>();

                    for (int i = 0; i < plList.size(); i++) {
                        List<PlanBean> planList = new ArrayList<>();

                        JSONArray obj = planObj.getJSONArray(plList.get(i));
//                        prop.put("creativeId",obj.get)
                        for (int n = 0; n < obj.size(); n++) {
                            JSONObject propJson = obj.getJSONObject(n);
                            if(propJson.get("totalCost")!=null&& Double.valueOf(propJson.get("totalCost").toString())>0){
                                Map<String, Object> prop = new HashMap<>();
                                prop.put("creativeId", propJson.get("creativeId"));
                                prop.put("delivery", propJson.get("delivery"));
                                prop.put("clicks", propJson.get("clicks"));
                                prop.put("totalCost", propJson.get("totalCost"));
                                prop.put("planId", propJson.get("planId"));
                                prop.put("datetimeStr", Datetime);
                                String AdId = dealCreativesDao.queryAdUserId(propJson.get("planId").toString());
                                Double service_rate = dealCreativesDao.queryServiceRate(AdId);
                                prop.put("service_rate",service_rate);
                                propMaps.add(prop);
                            }

                        }
                    }
                    System.out.println(propMaps.toString());
                    System.out.println("=====================" + propMaps.size());
                    if (propMaps.size() > 0) {
                        logger.info("准备更新的创意条数为：" + propMaps.size());
                        dealCreativesDao.UpdateCreatives(propMaps);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("调用智子云接口失败，原因：", e);
            }
        }

    }


    public static void main(String[] args) throws Exception {
        String[] planIds = new String[]{"syXzz0FgTHG", "szJL90umYGQ", "syXCP0V0HCg", "szm6Z0DVFde", "syXAU0HCebu","szdPW0HMHDO","syXwK0kUcAo","syVAU0fOaRy","sz8rf0iMRcA"};
        Map<String, Object> parm = new HashMap<>();
        parm.put("starttime", "2017-10-06");
        parm.put("endtime", "2017-09-06");
        parm.put("planids", planIds);
        JSONObject rspObject = ZhiZiYunUtil.getZhiZiYunData("rtbreport/getCreativesByPlan", parm);
        System.out.println(rspObject.toString());
    }
}
